package com.hb.android.autoreboot;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class RebootService extends Service {

    private static final String TAG = "RebootService测试";

    private static boolean isTestIng = false;
    private static boolean startCountDown = false;

    private int testTotalNumber = 1;  // 循环测试总次数
    private int currentNumber = 0;  // 当前已完成次数
    private int testIntervalTime = 10; // 10秒重启一次

    private PowerManager powerManager = null;
    private PowerManager.WakeLock wakeLock = null;

    @Override
    public void onCreate() {
        super.onCreate();
        Utils.logD(this, TAG, "onCreate executed");
    }

    @SuppressLint("WakelockTimeout")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Utils.logD(this, TAG, "onStartCommand executed");

        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        SharedPreferences sharedPreferences = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE);
        if (sharedPreferences == null) {
            return super.onStartCommand(intent, flags, startId);
        }

        currentNumber = sharedPreferences.getInt("currentNumber", 0);
        testTotalNumber = sharedPreferences.getInt("testTotalNumber", 1);
        testIntervalTime = sharedPreferences.getInt("testIntervalTime", 10);
        isTestIng = sharedPreferences.getBoolean("isTestIng", false);

        // 亮屏
        wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, MainActivity.class.getSimpleName());
        if (wakeLock != null) {
            wakeLock.acquire();
        }
        if (isTestIng) {
            startCountDown = true;
            handler.postDelayed(runnable, 2000);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 要做的事情
            updateView();
            if (startCountDown) {
                // 每隔1秒执行一次
                handler.postDelayed(this, 1000);
            }
        }
    };

    private void updateView() {
        if (isTestIng) {
            testIntervalTime -= 1;
            if (testIntervalTime > 0) {
                Utils.logD(this, TAG, "updateView: 倒计时：" + Utils.calculatePlayTime(testIntervalTime));
            } else {
                startCountDown = false;
                if (currentNumber < testTotalNumber) {
                    currentNumber += 1;
                    wakeLock.release();
                    doReboot();
                    stopSelf();
                } else {
                    isTestIng = false;
                    SharedPreferences.Editor editor = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE).edit();
                    editor.putString("lastResult", "最后一次测试结果：" + testTotalNumber + " 次测试已全部完成！");
                    editor.putBoolean("isShowLastResult", false);
                    editor.putBoolean("isTestIng", false);
                    editor.apply();
                    try {
                        if (MainActivity.testButton != null) {
                            MainActivity.testButton.setEnabled(true);
                            MainActivity.testIntervalEdit.setEnabled(true);
                            MainActivity.testNumberEdit.setEnabled(true);
                            Toast.makeText(this, "测试全部完成", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void doReboot() {
        SharedPreferences.Editor editor = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE).edit();
        editor.putString("lastResult", "最后一次测试结果：总循环次数:" + testTotalNumber + " 次，已成功完成:" + currentNumber + " 次");
        editor.putBoolean("isShowLastResult", true);
        editor.putInt("currentNumber", currentNumber);
        editor.apply();

        // 重启
        try {
            SharedPreferences sharedPreferences = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE);
            if (sharedPreferences == null) {
                return;
            }
            isTestIng = sharedPreferences.getBoolean("isTestIng", false);
            if (isTestIng) {
                Utils.logW(this, TAG, "重启");
                powerManager.reboot("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Utils.logD(this, TAG, "onDestroy executed");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}